﻿namespace Digitalmes.Application.Common.Strategies;

public static class StrategyServiceCollectionExtensions
{
    /// <summary>
    /// 注册业务策略，其中策略必须有设置 <see cref="StrategyAttribute"/> 特性。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection RegisterStrategy<T>(this IServiceCollection services)
        where T : IStrategy
    {
        return services.RegisterStrategy(typeof(T));
    }

    /// <summary>
    /// 注册业务策略，其中策略必须有设置 <see cref="StrategyAttribute"/> 特性。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="implType">实现 <see cref="IStrategy"/> 接口的类型。</param>
    /// <returns></returns>
    /// <exception cref="InvalidOperationException"></exception>
    public static IServiceCollection RegisterStrategy(this IServiceCollection services, Type implType)
    {
        var attr = implType.GetCustomAttribute<StrategyAttribute>()
            ?? throw new InvalidOperationException($"业务策略 [{implType.Name}] 必须设置 [BusinessPolicyAttribute] 特性。");
        services.AddKeyedTransient(typeof(IStrategy), attr.Name, implType);
        return services;
    }
}
